package com.zhanghe.wzq.handler.request;

import com.zhanghe.wzq.User;
import com.zhanghe.wzq.command.request.LoginRequest;
import com.zhanghe.wzq.command.response.LoginResponse;
import com.zhanghe.wzq.data.Attributes;
import com.zhanghe.wzq.data.UserChannelManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

/**
 * LoginRequestHandler
 *
 * @author Clevo
 * @date 2018/12/23
 */
@Slf4j
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequest loginRequest) throws Exception {
        LoginResponse response = new LoginResponse();
        String id = UUID.randomUUID().toString();
        response.setId(id);
        response.setName(loginRequest.getName());
        log.debug("登录回复:{}",response);
        UserChannelManager.getInstance().addUser(id,channelHandlerContext.channel());
        User user = new User();
        user.setId(id);
        user.setUserName(loginRequest.getName());
        channelHandlerContext.channel().attr(Attributes.USER).set(user);
        channelHandlerContext.channel().writeAndFlush(response);
    }
}
